package com.shujia.hbase.javacode;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class SortSplit {
    public static void main(String[] args) throws Exception {


        /**
         *
         * 对数据进行排序切分，建索引
         *
         *
         */


        ArrayList<Long> ids = new ArrayList<>();

        HashMap<Long, String> map = new HashMap<>();

        BufferedReader bufferedReader = new BufferedReader(new FileReader("java/data/students.txt"));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            Long s_id = Long.parseLong(line.split(",")[0]);

            ids.add(s_id);

            //学号作为key学生信息作为value
            map.put(s_id, line);

        }


        //对学号进行自然顺序排序
        Collections.sort(ids);


        /**
         * 对数据进行切片
         * 1-333
         * 334-666
         * 667-1000
         */


        /**
         * 索引
         *
         * 0,,1500100001,1500100333
         *
         */

        BufferedWriter indexWriter = new BufferedWriter(new FileWriter("java/data/hbase/index"));


        int fileNUm = 3;

        int i = ids.size() / fileNUm;

        int f = 0;

        int flag = i;

        BufferedWriter writer = new BufferedWriter(new FileWriter("java/data/hbase/data/" + f));


        Long startKey = ids.get(0);

        Long endKey = 0l;


        for (Long id : ids) {

            if (flag == 0 && f != 2) {


                /**
                 * 多前一个文件建立索引
                 *
                 */
                String index = f + "," + startKey + "," + endKey;

                indexWriter.write(index);
                indexWriter.newLine();

                writer.close();

                flag = i;
                f++;
                writer = new BufferedWriter(new FileWriter("java/data/hbase/data/" + f));

                startKey = id;
            }
            String info = map.get(id);
            writer.write(info);

            endKey = id;

            writer.newLine();
            writer.flush();

            flag--;

        }

        String index = f + "," + startKey + "," + endKey;

        indexWriter.write(index);
        indexWriter.newLine();

        writer.close();

        indexWriter.close();

    }
}
